package com.meadin.agent.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.zip.GZIPInputStream;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicNameValuePair;

import com.meadin.agent.domain.HttpEntitiy;

public class HttpRequestUtils {

	// post请求
	public static String sendPostForm(String url, Map<String, String> map) {
		BufferedReader in = null;
		String result = "";
		try {
			HttpEntitiy httpEntitiy = HttpProxy.getProxy(url);
			HttpPost httpPost = httpEntitiy.getPost();
			CloseableHttpClient client = httpEntitiy.getClient();
			httpPost.setHeader("accept", "text/html, */*");
			httpPost.setHeader("connection", "Keep-Alive");
			httpPost.setHeader("Accept-Encoding", "gzip, deflate, br");
			httpPost.setHeader("Accept-Language", "gzip, deflate, br");
			// httpPost.setHeader("Content-Length", "67");
			httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
			httpPost.setHeader("User-Agent",
					"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.116 Safari/537.36");
			httpPost.setHeader("Host", "www.tripadvisor.cn");
			httpPost.setHeader("Origin", "https://www.tripadvisor.cn");
			httpPost.setHeader("X-Puid", "Wg1bGX8AAAEAALKnNLMAAAA@");
			httpPost.setHeader("X-Requested-With", "XMLHttpRequest");
			if (map != null) {
				List<NameValuePair> list = new ArrayList<>();
				list.add(new BasicNameValuePair("plSeed", map.get("plSeed")));
				list.add(new BasicNameValuePair("showSnippets", map.get("showSnippets")));
				list.add(new BasicNameValuePair("zfp", map.get("zfp")));
				list.add(new BasicNameValuePair("zff", map.get("zff")));
				list.add(new BasicNameValuePair("cat", map.get("cat")));
				list.add(new BasicNameValuePair("offset", map.get("offset")));
				list.add(new BasicNameValuePair("reqNum", map.get("reqNum")));
				list.add(new BasicNameValuePair("zfc", map.get("zfc")));
				list.add(new BasicNameValuePair("changeSet", map.get("changeSet")));
				UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "UTF-8");
				httpPost.setEntity(entity);
				System.out.println("+=================================" + map.get("offset"));
			}

			HttpResponse httpResponse = client.execute(httpPost);
			InputStream ins = httpResponse.getEntity().getContent();
			InputStreamReader isr = new InputStreamReader(ins, "utf-8");
			in = new BufferedReader(isr);

			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
			return result;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		return null;
	}

	// post请求
	public static String sendPostForm1(String url, String map) {

		PrintWriter out = null;
		BufferedReader in = null;
		String result = "";

		try {
			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			URLConnection conn = realUrl.openConnection();
			// 设置通用的请求属性
			conn.setRequestProperty("accept", "text/html, */*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("Accept-Encoding", "gzip, deflate, br");
			conn.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.8");
			conn.setRequestProperty("Content-Length", "67");
			conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
			conn.setRequestProperty("User-Agent",
					"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.116 Safari/537.36");
			conn.setRequestProperty("Host", "www.tripadvisor.cn");
			conn.setRequestProperty("Origin", "https://www.tripadvisor.cn");
			conn.setRequestProperty("X-Puid", "Wg1bGX8AAAEAALKnNLMAAAA@");
			conn.setRequestProperty("X-Requested-With", "XMLHttpRequest");
			conn.setDoOutput(true);
			conn.setDoInput(true);
			// 获取URLConnection对象对应的输出流
			out = new PrintWriter(conn.getOutputStream());
			// 发送请求参数
			if (StringUtils.isNotBlank(map)) {

				out.print(map);
			} else {
				out.print("");
			}
			// flush输出流的缓冲
			out.flush();
			InputStream in1 = conn.getInputStream();
			GZIPInputStream gzin = new GZIPInputStream(in1);
			InputStreamReader isr = new InputStreamReader(gzin, "utf-8");

			in = new BufferedReader(isr);

			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
			System.out.println(result);
		} catch (Exception e) {
			System.out.println("发送 POST 请求出现异常！" + e);
			e.printStackTrace();
		}
		// 使用finally块来关闭输出流、输入流
		finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		return result;
	}

	/**
	 * 
	 * @ClassName:HttpRequestUtils.java
	 * @ClassDescribe:
	 * @auth:Liu Yongsheng
	 * @createDate:2017年11月15日 下午3:41:33
	 * @updateAuth:
	 * @updateDate:
	 * @version
	 * @param urlStr
	 */
	public static void sendgetByProxy(String urlStr) {

		BufferedReader in2 = null;
		String result = "";
		try {
			URL url = new URL(urlStr);
			// 创建代理服务器
			InetSocketAddress addr = new InetSocketAddress("218.92.220.67", 8080);
			Proxy proxy = new Proxy(Proxy.Type.HTTP, addr); // http 代理

			HttpURLConnection connection = (HttpURLConnection) url.openConnection(proxy);// proxy

			connection.setRequestMethod("GET");
			connection.setUseCaches(false);
			connection.setReadTimeout(8000);
			connection.setConnectTimeout(8000);
			connection.setInstanceFollowRedirects(false);
			connection.setRequestProperty("User-Agent",
					"Mozilla/5.0 (Windows NT 10.0; WOW64; rv:46.0) Gecko/20100101 Firefox/46.0");

			InputStream in = connection.getInputStream();
			in2 = new BufferedReader(new InputStreamReader(in));
			String line;
			while ((line = in2.readLine()) != null) {
				// 遍历抓取到的每一行并将其存储到result里面
				result += line + "\n";
			}

			System.out.println(result);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}